#!/usr/bin/env python3
# coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
def CaculateCost(Vector_theta,Matrix_x,Vector_Y):
   cost=0
   for i in range(len(Matrix_x[0])):
     single=0  	
     for j in range(len(Vector_theta)):
         single+=Matrix_x[j][i]*Vector_theta[j]
     single=(single-Vector_Y[i])*(single-Vector_Y[i])
     cost+=0.5*single
   return cost

def CaculateDerviation(i,Vector_theta,Vector_Y,Matrix_x):
    dervition=0
    for j in range(len(Matrix_x[0])):
      single=0	
      for k in range(len(Vector_theta)):
          single+=Matrix_x[k][j]*Vector_theta[k]
      single=(single-Vector_Y[i])*Matrix_x[i][j]
      dervition+=single
    return dervition
num=np.zeros((2,14))
house_price = open("house_info.txt", 'r');
row = 0;
for line in house_price.readlines():
     line = line.strip('\n')
     strarry=line.split(" ")
     for i in range(len(strarry)):
         num[row][i]=float(strarry[i])
     row+=1
x=np.linspace(0,1,10)
Vector_Y=(np.array(num[1])-min(num[1]))/(max(num[1])-min(num[1]))
#Vector_Y=np.array(num[1])*0.001
print(Vector_Y)
theta=[0.2,1]                                                       #initialize the theta(parameters)
alpha=0.0002                                                        #initialize the steplength
matrix_x=np.zeros((2,14))
matrix_x[0]=np.ones((1,14))
matrix_x[1]=(np.array(num[0])-min(num[0]))/(max(num[0])-min(num[0]))
#matrix_x[1]=np.array(num[1])-2000
print(matrix_x[1])
print(CaculateCost(theta,matrix_x,Vector_Y))
plt.axis([0,1,0,1])
plt.ion()
for i in range(1500):
   plt.cla()
   plt.plot(matrix_x[1],Vector_Y,'*',x,x*np.array(theta[1])+np.array(theta[0]),'b-')
   plt.pause(0.2)
   temp_theta=np.zeros(2)
   for j in range(len(theta)):
     temp_theta[j]=theta[j]-alpha*CaculateDerviation(j,theta,Vector_Y,matrix_x)
   cost=CaculateCost(temp_theta,matrix_x,Vector_Y)
   print(cost)
   if  cost<0.04:
     break
   theta=temp_theta
plt.pause(10)
